//
//  FieldOrderSubListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/9/10.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "SerOrderSubListCell.h"
#import "SerOrderSubSectionHeader.h"
#import "SerOrderSubSectionFooter.h"

#import "FieldOrderDetailViewController.h"
#import "SelPayMethodViewController.h"
#import "FieldOrderDetailViewController.h"

#import "EvaluateOrderViewController.h"
#import "FieldOrderSubListViewController.h"

@interface FieldOrderSubListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <OrderListModel *>*dataArray;

@property (nonatomic, strong) NSMutableArray *footerConfigArray;

//这个枚举实际对应的是分段的排列
@property (nonatomic, assign) FieldOrderType type;

//这个用来请求实际对应分段的数据
@property (nonatomic, assign) NSInteger requestType;

@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation FieldOrderSubListViewController

- (instancetype)initWithIndex:(NSInteger)index {
    self = [super init];
    if (self) {
        
        switch (index) {
            case 0:{

            } break;
            case 1:{
                self.type = FieldOrderType_WaitPay;
            } break;
            case 2:{
                self.type = FieldOrderType_WaitEvaluate;
            } break;
            default:
                break;
        }
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshParam];
    [self request_orderList];
}

- (void)refreshParam {
    
    self.pageSize = 20;
    self.pageNum = 1;
    self.dataArray = @[].mutableCopy;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    
    [self.tableview reloadData];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 100;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (self.dataArray[section].uodStatus == SerCellOrderType_recOrder) {
        return 45;
    }
    return 90;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    SerOrderSubSectionHeader *headView = [[NSBundle mainBundle] loadNibNamed:@"SerOrderSubSectionHeader"owner:nil options:nil].firstObject;
    if (self.dataArray.count > section) {
        [headView fillHeaderVithModel:self.dataArray[section]];
    }
    return  headView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    SerOrderSubSectionFooter *footerView = [[NSBundle mainBundle] loadNibNamed:@"SerOrderSubSectionFooter"owner:nil options:nil].firstObject;
    
    if (self.dataArray.count > section) {
        [footerView fillFooterVithModel:self.dataArray[section]];
    }
    
    WEAKSELF
    footerView.SerOrderSubSectionFooterBlock = ^(NSInteger index) {
        
        switch ((SerCellOrderActionType)index) {
            case SerCellOrderActionType_cancle:{
                
                [TT_Alert alert:@"是否确定取消订单？" cancleBtnTitle:@"取消" cancleAction:^{
                    
                } doneBtnTitle:@"确定" doneAction:^{
                    [weakSelf request_dealOrderWithIndex:section Type:SerCellOrderType_cancle];
                }];
                
            } break;
            case SerCellOrderActionType_servicePass:{
                //确认完成服务
                [weakSelf request_dealOrderWithIndex:section Type:SerCellOrderType_evaluate];
            } break;
            case SerCellOrderActionType_evaluate:{
                
                EvaluateOrderViewController *vc = [[EvaluateOrderViewController alloc] init];
                vc.model = self.dataArray[section];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            case SerCellOrderActionType_delete:{
                
                [TT_Alert alert:@"是否确定删除订单？" cancleBtnTitle:@"取消" cancleAction:^{
                    
                } doneBtnTitle:@"确认" doneAction:^{
                    [weakSelf request_delOrderWithIndex:section];
                }];
                
            } break;
            default:
                break;
        }
    };
    
    return  footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 90;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count > indexPath.section) {

        FieldOrderDetailViewController *vc = [[FieldOrderDetailViewController alloc] init];
        vc.orderId = self.dataArray[indexPath.section].uoId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SerOrderSubListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SerOrderSubListCellID"];
    
    if (self.dataArray.count > indexPath.section) {
        [cell fillCellWithModel:self.dataArray[indexPath.section]];
    }
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}


- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"SerOrderSubListCell" bundle:nil] forCellReuseIdentifier:@"SerOrderSubListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{

            [weakSelf refreshParam];
            [weakSelf request_orderList];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{

            weakSelf.pageNum ++;
            [weakSelf request_orderList];

        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (NSMutableArray *)footerConfigArray {
    /*
     订单状态: 1待支付 2待发货 3已发货 4已完成 5已取消 6退款申请 7退款完成
     footerShowType 订单状态
     btnArray 按钮配置
      btnTitle按钮标题
      btnAction按钮行为 对应 OrderSubListSectionFooterViewAction枚举
      btnColor按钮颜色 0黑色 1红色
     订单状态: 1待支付 2待发货 3已发货 4已完成 5已取消 6退款申请 7退款完成
     */
    if (!_footerConfigArray) {
        _footerConfigArray = @[].mutableCopy;
        _footerConfigArray = @[
            
            
            //待付款
            @{@"footerShowType": @(SerCellOrderType_waitPay),
              @"btnArray":@[@{@"btnTitle":@"取消订单",
                              @"btnAction":@(SerCellOrderActionType_cancle),
                              @"btnColorType":@(0)}],
            },
            
            //待评价
            @{@"footerShowType": @(SerCellOrderType_evaluate),
              @"btnArray":@[@{@"btnTitle":@"评价",
                              @"btnAction":@(SerCellOrderActionType_evaluate),
                              @"btnColorType":@(1)}]
            },
            
            //系统取消
            @{@"footerShowType": @(SerCellOrderType_sysClose),
              @"btnArray":@[]
            }
        ].mutableCopy;
    }

    return _footerConfigArray;
}

- (void)request_orderList {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyOrder];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"uoUserId"];
    [t setValue:@"3" forKey:@"uodOrderType"];
    [t setValue:@"2" forKey:@"uodIsDel"];

    if (self.type) {
        [t setValue:@(self.type) forKey:@"status"];
    }

    [dic setValue:t forKey:@"t"];
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                        
                if ([list isKindOfClass:[NSArray class]]) {

                    if (self.pageNum == 1) {
                        self.dataArray = @[].mutableCopy;
                    }
                    
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            OrderListModel *model = [OrderListModel modelWithDictionary:listDic];

                            NSArray *userOrderGoodList = [listDic valueForKey:@"userOrderGoodList"];
                            
                            if ([userOrderGoodList isKindOfClass:[NSArray class]]) {
                                model.userOrderGoodList = @[].mutableCopy;
                                
                                for (int j = 0; j < userOrderGoodList.count; j++) {
                                    NSDictionary *userOrderGoodListDic = userOrderGoodList[j];
                                    OrderGoodsModel *goodsModel = [OrderGoodsModel modelWithDictionary:userOrderGoodListDic];
                                    
                                    [model.userOrderGoodList addObject:goodsModel];
                                }
                            }
                                                                       
                            //获取底部数据配置
                            for (NSDictionary *bottomDic in self.footerConfigArray) {
                                
                                NSInteger footerShowType = [[bottomDic valueForKey:@"footerShowType"] integerValue];

                                if (footerShowType == (SerCellOrderType)model.uodStatus) {
                                    model.bottomModel = [OrderBottomModel modelWithDictionary:bottomDic];
                                    
                                    NSArray *btnArray = [bottomDic valueForKey:@"btnArray"];
                                    if ([btnArray isKindOfClass:[NSArray class]]) {
                                        model.bottomModel.btnArray = @[].mutableCopy;
                                        for (NSDictionary *btnDic in btnArray) {
                                            OrderBtnModel *btnModel = [OrderBtnModel modelWithDictionary:btnDic];
                                            [model.bottomModel.btnArray addObject:btnModel];
                                        }
                                    }
                                }
                            }

                            [self.dataArray addObject:model];
                        }
                    }
                    
                    if (weakSelf.dataArray.count == 0) {
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoOrder btnTitle:@"" didPressButton:^{}];
                    }
                    [self.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)request_dealOrderWithIndex:(NSInteger)index Type:(SerCellOrderType)type{
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].uodOrderId forKey:@"orderId"];
    [dic setValue:self.dataArray[index].uodId forKey:@"uodId"];
    [dic setValue:@((SerCellOrderType)type) forKey:@"status"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_DealOrder];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
             if (code == 10000) {
                 
                 [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                 [SVProgressHUD dismissWithDelay:1];
                 [weakSelf refreshParam];
                 [weakSelf request_orderList];
                 
             } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {}];
}

//- (void)firstPayWithIndex:(NSInteger)index {
//
//    NSMutableDictionary *dic = @{}.mutableCopy;
//    [dic setValue:self.dataArray[index].uoId forKey:@"orderId"];
//
//    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_PayOrderDJ];
//
//    WEAKSELF
//    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
//
//        if ([data isKindOfClass:[NSDictionary class]]) {
//            //请求成功
//            NSInteger code = [[data valueForKey:@"code"] integerValue];
//            if (code == 10000) {
//
//                NSDictionary *resultDic = [data valueForKey:@"data"];
//                SelPayMethodModel *model = [SelPayMethodModel modelWithDictionary:resultDic];
//                SelPayMethodViewController *vc = [[SelPayMethodViewController alloc] init];
//                vc.model = model;
//                [weakSelf.navigationController pushViewController:vc animated:YES];
//            } else {
//                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
//                [SVProgressHUD dismissWithDelay:1];
//            }
//        }
//    } FailedBlock:^(NSError * _Nonnull error) {
//    }];
//}

#pragma mark 删除订单
- (void)request_delOrderWithIndex:(NSInteger)index {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].uodOrderId forKey:@"orderId"];
    [dic setValue:self.dataArray[index].uodId forKey:@"uodId"];
    [dic setValue:@(1) forKey:@"isDel"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_DealOrder];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
             if (code == 10000) {
                 
                 [weakSelf refreshParam];
                 [weakSelf request_orderList];
                 [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                 [SVProgressHUD dismissWithDelay:1];
                 
             } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {}];
}



@end
